<script>
export default {
  name:'user',
  mounted() {
    this.roleIds=[]
    this.userDto=[]
    this.selectUserByCondition()
    this.$http.get("role/selectAll").then((resp)=>{
      this.tableRoles=resp.data.data;
      this.tableRole = this.tableRoles.slice(0,10)
    }).catch(error=>{

    })
    },
  methods:{
    //select选择控制
    filterMethod(query){
      if (query == "") {
        return  this.tableRole = this.tableRoles.slice(0,10)
      }else{
        let result = []
        this.tableRoles.forEach(val=>{
          if (val.roleName.indexOf(query) != -1) result.push(val)
        })
        this.tableRole = result.slice(0,10)

      }

    },

    //普通删除
    deleteByIdUser(row){
      this.userIds=[]
      this.userIds.push(row.userId)
      this.$http.post("user/delete",this.userIds).then((resp)=>{
          if (resp.data.code == 200){
            this.$message({
              showClose: true,
              message: '恭喜你，删除成功',
              type: 'success'
            });
            this.selectUserByCondition()
          }else if (resp.data.code == 500){
            this.$message({
              showClose: true,
              message: '删除失败',
              type: 'warning'
            });
          }
      }).catch(error=>{

      })
    },
    //批量删除
    deleteByIdsUser(done){
      if (this.userIds.length == 0){
        this.$message({
          message: '请先选择用户',
          type: 'warning'
        });
        return

      }
      this.$confirm('是否批量删除？')
          .then(_ => {
          this.$http.post("user/delete",this.userIds).then((resp)=>{
            if (resp.data.code == 200){
              this.$message({
                showClose: true,
                message: '恭喜你，删除成功',
                type: 'success'
              });
              this.selectUserByCondition()
            }
            done();
          }).catch(error=>{

          })

          })
          .catch(_ => {});
    },
    //多选
    handleSelectionChange(val) {
      this.roleIds=[]
      for (let i = 0; i < val.length; i++) {
        this.userIds.push(val[i].userId)
      }
      console.log(this.userIds)
    },

    selectUserByCondition(){
      console.log(this.user)
      delete this.user.sex
      this.$http.post("user/select?current="+this.currentPage+"&size="+this.pageSize+"",this.user).then((resp)=>{
        this.tableData=resp.data.data.list;
        this.total = resp.data.data.total;
        console.log(this.tableData)
      }).catch(error=>{

      })
    },

    //筛选值
    searchSelect(data){
      this.user.roles = data
      console.log(this.user.roles)
    },
    //关闭弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.user={}
            done();
          })
          .catch(_ => {});
  },
    updateUser(row){
      this.dialogVisible=true;
      console.log(row);
      this.user=row

      this.roles=row.roles
      this.isShow = false
    },
    //弹出框
    addUser(){
      this.isShow = true
      this.user={}
      this.roles=[]
      this.dialogVisible=true;

      // this.$http.post("user/addUser",this.user).then((resp)=>{
      //
      // })
    },
    addOrUpdateUser(){
      this.roleIds=[]
      for (var i=0;i<this.roles.length;i++){
        this.roleIds.push(this.roles[i].roleId)
      }
      console.log(this.user)

      if (this.user.updateTime != "" && this.user.updateTime != null){
        //修改
        // delete this.user.role;
        // this.userDto=this.user
        // this.userDto.role = this.roles
        console.log(this.user)
        this.$http.put("user/update",this.user).then((resp)=>{
          if (resp.data.code==200){
            this.$message({
              showClose: true,
              message: '恭喜你，修改成功',
              type: 'success'
            });
            this.dialogVisible=false;
            this.user={}
            this.selectUserByCondition()
          }
        }).catch((error)=>{
          console.log(error)
        })

      }else {
        //添加
        this.$http.post("user/add",this.user).then((resp)=>{
          if (resp.data.code==200){
            this.$message({
              showClose: true,
              message: '恭喜你，添加成功',
              type: 'success'
            });
          }
          this.dialogVisible=false;
          this.user={}
          this.selectUserByCondition()
        }).catch((error)=>{
          console.log(error)
        })
      }

    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.selectUserByCondition()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.selectUserByCondition()
    },

  },
  data() {
    var checkEmail = (rule, value,callback) =>{//验证邮箱
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if(this.user.email != '' && !regEmail.test(this.user.email)) {
        callback(new Error('请输入有效的邮箱'));
      }
    }
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入名称'));
      } else {
        if (value.length>20) {
          callback(new Error('名称过长'));
        }
        callback();
      }
    }
    var validateLoginName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录名称'));
      } else {
        if (value.length>20) {
          callback(new Error('登录名称过长'));
        }
        callback();
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (value.length>20) {
          callback(new Error('密码过长'));
        }
        callback();
      }
    };
    return {

      rules: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        loginName:[
          {validator: validateLoginName, trigger: 'blur' }
        ],
        name:[
          {validator: validateName, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号必填', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        email:[{ required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator: checkEmail, trigger: "blur" }
        ]

      },
      //dto
      userDto:[
        {
          role:[]
        }
      ],
      //多选
      multipleSelection: [],
      userIds:[],
      options: [
        {
          value: "",
          label: '无'
        },
        {
        value: "启用",
        label: '启用'
      }, {
        value: "禁用",
        label: '禁用'
      }],
      label:"",
      roles: [],
      roleId:'',
      roleIds: [{

      }],
      dialogVisible: false,
      //分页
      currentPage: 1,
      pageSize:5,
      total:10,
      tableRoles:[
        {
          roleId:"0",
          roleName: "",

        }
      ],

      tableRole:[
          {
            roleId:"0",
            roleName: "",

      }
      ],

      user:{
        loginName:"",
        name:"",
        password:"",
        sex:"",
        userId:"",
        phone:"",
        email:"",
        status:"",
        updateTime:"",
        roles:[]

      },
      tableData: [{
        role:[{
            roleName:''
        }]
      }]
    }
  }
}
</script>

<template>
  <div>
      <h1 style="margin-left: 2%;top: 14px;position: relative">用户管理</h1>
    <div style="position: relative;margin-top:2%">

      <el-input
          placeholder="请输入用户id"
          v-model="user.userId"
          style="width: 200px"
          clearable>
      </el-input>

      <el-input
          placeholder="请输入用户联系电话"
          v-model="user.phone"
          style="width: 200px;margin-left: 2px"
          clearable>
      </el-input>

      <el-select v-model="user.status" placeholder="请选择"
      style="margin-left: 2px;width: 100px;">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        style="width: 100px">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" style="margin-left: 15px" @click="selectUserByCondition">搜索</el-button>
      <el-button type="danger" round style="float: right;margin-right: 35px;position: relative" @click="deleteByIdsUser">批量删除</el-button>
      <el-button type="primary" round style="float: right;margin-right: 19px;position: relative" @click="addUser">添加用户</el-button>
    </div>



  <el-table
      :data="tableData"
      border
      ref="multipleTable"
      style="width: 100%;margin-top: 1%;margin-left: 1%;border-radius: 2px"
      @selection-change="handleSelectionChange">
    <el-table-column
        type="selection"
        width="55">
    </el-table-column>
    <el-table-column
        fixed
        prop="userId"
        label="用户id"
        width="220">
    </el-table-column>
    <el-table-column
        prop="name"
        label="姓名"
        width="120">
    </el-table-column>
    <el-table-column
        prop="sex"
        label="性别"
        width="80">
    </el-table-column>
    <el-table-column
        prop="status"
        label="状态"
        width="80">
    </el-table-column>

    <el-table-column
        prop="phone"
        label="联系电话"
        width="150">
    </el-table-column>

    <el-table-column
        prop="email"
        label="邮箱"
        width="200">
    </el-table-column>


    <el-table-column
        align="center"
        prop="roles"
        label="角色名称"
        width="170">
      <template slot-scope="scope" >
        <div v-for="(item, index) in scope.row.roles" :key="index">
          {{item.roleName}}
        </div>
      </template>
    </el-table-column>

    <el-table-column
        fixed="right"
        label="操作"
        width="170">
      <template slot-scope="scope">
        <el-button @click="updateUser(scope.row)" type="text" size="small">编辑</el-button>
        <el-button @click="deleteByIdUser(scope.row)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 2%"
    >
    </el-pagination>



<!--添加form表单-->
    <el-dialog
        title="编辑用户"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-form ref="form" :model="user" label-width="80px" :rules="rules">
        <el-form-item label="登录名称" prop="loginName">
          <el-input v-model="user.loginName" ></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>

        <el-form-item label="性别">
        <el-radio v-model="user.sex" label="男">男</el-radio>
        <el-radio v-model="user.sex" label="女">女</el-radio>
        </el-form-item>

        <el-form-item label="密码" prop="password"> <!--v-show="isShow"-->
          <el-input v-model="user.password" show-password></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>

        <el-form-item label="状态">
        <el-tooltip  placement="top">
          <el-switch
              v-model="user.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="启用"
              inactive-value="禁用">
          </el-switch>
        </el-tooltip>
        </el-form-item>

        <el-form-item label="选择角色">
          <el-select  v-model="roles"
                      value-key="roleId"
                      filterable
                      :filter-method="filterMethod"
                      multiple placeholder="请选择" style="width: 233px " @change="searchSelect">
            <el-option
                v-for="item in tableRole"
                :key="item.roleId"
                :label="item.roleName"
                :value="item"
            >

            </el-option>
          </el-select>

        </el-form-item>


      </el-form>
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addOrUpdateUser">确 定</el-button>

    </el-dialog>


  </div>
</template>

<style scoped>
.el-pagination{
  text-align: center;
}
</style>